package com.gitee.melin.bee.util;

import com.gitee.melin.bee.core.support.Result;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class RestTemplateUtils {

    public static <T> Result<String> postEntry(RestTemplate restTemplate, String uri, T entry) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> httpEntity = new HttpEntity<>(entry, headers);

        ParameterizedTypeReference<Result<String>> typeRef = new ParameterizedTypeReference<Result<String>>() {};
        return restTemplate.exchange(uri, HttpMethod.POST, httpEntity, typeRef).getBody();
    }

    public static <T> Result<String> postEntry(RestTemplate restTemplate, String uri, String key, Object value) {
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add(key, value);
        return postEntry(restTemplate, uri, multiValueMap);
    }

    public static <T> Result<String> postEntry(RestTemplate restTemplate, String uri,
                                               String key1, Object value1, String key2, Object value2) {

        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add(key1, value1);
        multiValueMap.add(key2, value2);
        return postEntry(restTemplate, uri, multiValueMap);
    }

    private static <T> Result<String> postEntry(RestTemplate restTemplate, String uri,
                                                MultiValueMap<String, Object> multiValueMap) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, headers);
        ParameterizedTypeReference<Result<String>> typeRef = new ParameterizedTypeReference<Result<String>>() {};
        return restTemplate.exchange(uri, HttpMethod.POST, httpEntity, typeRef).getBody();
    }
}
